package net

import (
	"log"
	"net/http"

	"github.com/gorilla/websocket"
)

type server struct {
	addr         string
	serverRouter *Router
}

func NewServer(addr string) *server {
	return &server{
		addr: addr,
	}
}

// 这个router起传递作用，将（文件名和函数）用于传给wsRouter去执行
func (s *server) SetServerRouter(r *Router) {
	s.serverRouter = r
}

// 启动服务
func (s *server) Start() {
	http.HandleFunc("/", s.wsHandler)
	err := http.ListenAndServe(s.addr, nil)
	if err != nil {
		panic(err)
	}
}

// http升级websocket协议的配置
var wsUpgrader = websocket.Upgrader{
	// 允许所有CORS跨域请求
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func (s *server) wsHandler(w http.ResponseWriter, r *http.Request) {
	//升级为websocket
	wsConn, err := wsUpgrader.Upgrade(w, r, nil)
	if err != nil {
		//打印日志 同时 退出应用程序
		log.Println("websocket服务连接出错", err)
	}

	wsServer := NewWsServer(wsConn)
	wsServer.SetwsRouter(s.serverRouter)
	wsServer.Start()

}
